package com.smartdot.bluetoothidcarddemo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcV;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.smartdot.bluetoothidcarddemo.nfc.BaseNfcActivity;
import com.smartdot.bluetoothidcarddemo.utils.LogUtils;
import com.smartdot.bluetoothidcarddemo.utils.StatusBarUtil;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class NfcVActivity extends BaseNfcActivity {

    private TextView tv_nfc_type;
    private TextView tv_nfc_info;
    private TextView tv_nfc_data;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarColor(this, getColor(R.color.translate), true);
        StatusBarUtil.StatusBarLightMode(this);
        setContentView(R.layout.nfc_activity_layout);
        initView();
        resolveIntent(getIntent());

    }

    private void initView() {
        tv_nfc_type = findViewById(R.id.tv_nfc_type);
        tv_nfc_info = findViewById(R.id.tv_nfc_info);
        tv_nfc_data = findViewById(R.id.tv_nfc_data);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        resolveIntent(intent);
    }


    private void resolveIntent(Intent intent) {
        String action = intent.getAction();
        LogUtils.eNormal("luoli", "action:" + action);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            // 获取卡片的Id
            byte[] id = mTag.getId();
            String s = printHexString(id);
            tv_nfc_type.setText("技术标准：\r\n" + mTag);
            tv_nfc_info.setText("卡片id为:\r\n" + s);
            LogUtils.eNormal("luoli", "哈哈哈:" + s);
            String[] techList = mTag.getTechList();
            for (String tech : techList) {
                if (tech.equals(NfcV.class.getName())) {
//                    readNfcV();
                } else if (tech.equals(NfcA.class.getName())) {
//                    readNfcA();
                } else if (tech.equals(NfcB.class.getName())) {
//                    readNfcB();
                } else if (tech.equals(IsoDep.class.getName())) {
                    readIsoDep();
                }
            }
        }
    }

    private void readIsoDep() {
        IsoDep isodep = IsoDep.get(mTag);
        try {
            isodep.connect();
            //select the card manager applet
            byte[] mf = {(byte) '1', (byte) 'P',
                    (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y',
                    (byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F',
                    (byte) '0', (byte) '1',};
            String result = "";
            byte[] mfRsp = isodep.transceive(getSelectCommand(mf));
            LogUtils.eNormal("luoli", "mfRsp:" + HexToString(mfRsp));
            //select Main Application
            byte[] wht = {(byte) 0x41, (byte) 0x50,//此处以武汉通为例，其它的卡片参考对应的命令，网上可以查到
                    (byte) 0x31, (byte) 0x2E, (byte) 0x57, (byte) 0x48, (byte) 0x43,
                    (byte) 0x54, (byte) 0x43,};
            byte[] sztRsp = isodep.transceive(getSelectCommand(wht));

            byte[] balance = {(byte) 0x80, (byte) 0x5C, 0x00, 0x02, 0x04};
            byte[] balanceRsp = isodep.transceive(balance);
            LogUtils.eNormal("luoli", "balanceRsp:" + HexToString(balanceRsp));
            if (balanceRsp != null && balanceRsp.length > 4) {
                int cash = byteToInt(balanceRsp, 4);
                float ba = cash / 100.0f;
                result += "  余额：" + String.valueOf(ba);
                LogUtils.eNormal("luoli", "result:" + result);
                tv_nfc_data.setText("数据\r\n" + result + " 元");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                isodep.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private byte[] getSelectCommand(byte[] aid) {
        final ByteBuffer cmd_pse = ByteBuffer.allocate(aid.length + 6);
        cmd_pse.put((byte) 0x00) // CLA Class
                .put((byte) 0xA4) // INS Instruction
                .put((byte) 0x04) // P1 Parameter 1
                .put((byte) 0x00) // P2 Parameter 2
                .put((byte) aid.length) // Lc
                .put(aid).put((byte) 0x00); // Le
        return cmd_pse.array();
    }

    private String HexToString(byte[] data) {
        String temp = "";
        for (byte d : data) {
            temp += String.format("%02x", d);
        }
        return temp;
    }

    private int byteToInt(byte[] b, int n) {
        int ret = 0;
        for (int i = 0; i < n; i++) {
            ret = ret << 8;
            ret |= b[i] & 0x00FF;
        }
        if (ret > 100000 || ret < -100000)
            ret -= 0x80000000;
        return ret;
    }

    private void readNfcA() {
        NfcA nfcA = NfcA.get(mTag);
        try {
            nfcA.connect();
            boolean connected = nfcA.isConnected();
            LogUtils.eNormal("luoli", "connect结果==connected:" + connected);
            if (connected) {
                LogUtils.eNormal("luoli", "NfcA连接成功");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                nfcA.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void readNfcB() {
        NfcB nfcB = NfcB.get(mTag);
        try {
            nfcB.connect();
            boolean connected = nfcB.isConnected();
            LogUtils.eNormal("luoli", "connect结果==connected:" + connected);
            if (connected) {
                LogUtils.eNormal("luoli", "NfcB连接成功");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                nfcB.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //读取Ndef标签中数据
    private void readNfcV() {
        NfcV nfcV = NfcV.get(mTag);
        try {
            nfcV.connect();
            boolean connected = nfcV.isConnected();
            LogUtils.eNormal("luoli", "connect结果==connected:" + connected);
            if (connected) {
                LogUtils.eNormal("luoli", "NfcV连接成功");
            }
        } catch (IOException e) {
            LogUtils.eNormal("luoli", "connect异常" + e.toString());
            e.printStackTrace();
        } finally {
            try {
                nfcV.close();//关闭连接
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将字节数组遍历转换为16进制并拼接为String
     */
    private String printHexString(byte[] data) {
        StringBuffer s = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            String hex = Integer.toHexString(data[i] & 0xFF).toUpperCase();
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            if (i != data.length - 1) {
                s.append(hex + ":");
            } else {
                s.append(hex);
            }
        }
        return s.toString();
    }

    public void hh(View view) {

//        如果设置一个app的mainActivity为COMPONENT_ENABLED_STATE_DISABLED状态
//        则不会再launcher的程序图标中发现该app
        PackageManager packageManager = getPackageManager();
        ComponentName componentName = new ComponentName(this, NfcVActivity.class);
        int res = packageManager.getComponentEnabledSetting(componentName);
        if (res == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
                || res == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
            // 隐藏应用图标
            packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
        } else {
            // 显示应用图标
            packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
                    PackageManager.DONT_KILL_APP);
        }
    }
}
